<template>
  <div class="ebook-reader">
    <div id="read"></div>
  </div>
</template>

<script>
import {ebookMixin} from '../../utils/mixin'
// import {mapActions} from 'vuex'
import Epub from 'epubjs'

global.epub = Epub
export default {
  mixins:[ebookMixin],
  mounted () {
    // const baseUrl= 'http://127.0.0.1:8082/epub/'
    const fileName = this.$route.params.fileName.split('|').join('/')
    // this.$store.dispatch('setFileName',fileName).then(()=>{
    //   this.initEpub()
    // })
    this.setFileName(fileName).then(()=>{
      this.initEpub()
    })
    // console.log(`${baseUrl}${fileName}.epub`)
  },
  methods:{
   
    prevPage () {
      if(this.rendition){
        this.rendition.prev()
        this.hideTitleAndMenu()
      }
    },
    nextPage() {
      if(this.rendition){
        this.rendition.next()
        this.hideTitleAndMenu()
      }
    },
    toggleTitleAndMenu() {
      console.log('showMenu')
      // this.$store.dispatch('setMenuVisible',!this.menuVisible)
      if(this.menuVisible){
        this.setSettingVisible(-1)
      }
      this.setMenuVisible(!this.menuVisible)
    },
    hideTitleAndMenu() {
      // this.$store.dispatch('setMenuVisible',false)
      this.setMenuVisible(false)
      this.setSettingVisible(-1)
    },
    initEpub () {
      const url= 'http://127.0.0.1:8082/epub/'+this.fileName+'.epub'
      console.log('222',url)
      this.book = new Epub(url)
      this.setCurrentBook(this.book) // 将实例化的电子书对象存入vuex
      console.log('book',this.book)
      this.rendition = this.book.renderTo('read',{
        width:innerWidth,
        height:innerHeight,
        methods:'default'
      })
      this.rendition.display()
      this.rendition.on('touchstart',event=>{
        console.log('触摸开始',event)
        this.touchStartX= event.changedTouches[0].clientX //开始触摸屏幕时的x轴位置（第一只手）
        this.touchStartTime = event.timeStamp //开始触摸屏幕时的时间（第一只手）
      })
      this.rendition.on('touchend',event=>{
        console.log('触摸结束',event)
        const offsetX = event.changedTouches[0].clientX - this.touchStartX
        const time  = event.timeStamp - this.touchStartTime
        console.log('移动距离',offsetX,'触摸时间',time)
        if(time <500 && offsetX>40){ //从左向右滑动 前往上一页
          this.prevPage() 
        }else if(time<500 && offsetX <-40){ //从右向左滑动 前往下一页
          this.nextPage()
        }else{
          this.toggleTitleAndMenu()
        }
        event.preventDefault()
        event.stopPropagation()
      })
    }
  }
}
</script>

<style>

</style>